//
//  YYECourseBuyViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2018/1/18.
//  Copyright © 2018年 胡波. All rights reserved.
//

#import "YYECourseBuyViewController.h"
#import "YYECourseBuyInfoTableViewCell.h"
#import "YYERechargeTableViewCell.h"
#import "YYEBalanceSwitchTableViewCell.h"
#import "NSStringExt.h"
#import "PayModel.h"
//#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "WXApiObject.h"

@interface YYECourseBuyViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) YYEBaseTableView *tableView;
@property (nonatomic,strong) UILabel *payMoneyLabel;
@property (nonatomic,strong) YYECourseIntroModel *model;
@property (nonatomic,strong) NSString *payMoney;
@property (nonatomic,strong) NSString *payWay;


@end

@implementation YYECourseBuyViewController

static NSString *courseInfoCell = @"courseInfo";
static NSString *acountCell = @"acountCell";
static NSString *paymentCell = @"paymentCell";

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"购买课程";
    
    [self configUI];
    
    [self configBottomView];
    
    [self loadData];
    
//    //支付取消通知事件
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payCancel) name:@"kPayCancelNotification" object:nil];
    
//    //支付成功通知事件
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(paySuccess) name:@"kPaySuccessNotification" object:nil];
}

//- (void)paySuccess
//{
//
////    //充值或提现成功通知事件
////    [[NSNotificationCenter defaultCenter] postNotificationName:@"kchargeOrDepositSuccessNotification" object:nil];
//
//    [self.view makeToast:@"购买成功"];
//
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.navigationController popToRootViewControllerAnimated:YES];
//    });
//}

- (void)loadData {
    
    NSDictionary *dic = @{
                          @"uid":[LoginModel shareLogin].uid,
                          @"username":[LoginModel shareLogin].username,
                          @"token":[LoginModel shareLogin].token,
                          @"cid":self.cid
                          };
    [AFNHelper post:Get_info parameters:dic success:^(id responseObject) {
        
        if ([responseObject[@"status"] isEqual:@1]) {
            self.model = [YYECourseIntroModel mj_objectWithKeyValues:responseObject[@"data"]];
            [self.tableView reloadData];
            
            if (self.model.balance.floatValue > 0) {

                float money = self.model.price.floatValue - self.model.balance.floatValue;
                if (money > 0) {
                    
                    self.payMoney = [NSString stringWithFormat:@"%.2f",money];
                    
                }
                else {
                    self.payMoney = @"0.00";
                }
            }
            else {
                self.payMoney = self.model.price;
            }
            
            self.payMoneyLabel.text = [NSString stringWithFormat:@"￥%@",self.payMoney];
            
            
            // 余额没有或不足时你默认微信支付
            self.payWay = @"2";
            NSInteger selectedIndex = 0;
            NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:selectedIndex inSection:2];
            [self.tableView selectRowAtIndexPath:selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                self.payWay = @"2";

            });

        }
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        
    }];
    
    
}

- (void)configUI {
    
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = GeneralBackColor;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[YYECourseBuyInfoTableViewCell class] forCellReuseIdentifier:courseInfoCell];
    [self.tableView registerClass:[YYEBalanceSwitchTableViewCell class] forCellReuseIdentifier:acountCell];
    [self.tableView registerClass:[YYERechargeTableViewCell class] forCellReuseIdentifier:paymentCell];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(UIEdgeInsetsZero);
        make.left.right.top.equalTo(self.view);
        make.bottom.equalTo(self.view.bottom).offset(-45);
    }];
    
}

- (void)configBottomView {
    
    UIView *contentView = [[UIView alloc]init];
    contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:contentView];
    
    UILabel *moneyLabel = [[UILabel alloc]init];
    moneyLabel.text = @"实付金额：";
    moneyLabel.textColor = [UIColor blackColor];
    moneyLabel.font = [UIFont systemFontOfSize:16];
    [contentView addSubview:moneyLabel];
    
    self.payMoneyLabel = [[UILabel alloc]init];
    self.payMoneyLabel.textColor = [UIColor redColor];
    self.payMoneyLabel.font = [UIFont systemFontOfSize:16];
//    self.payMoneyLabel.text = @"¥132";
    [contentView addSubview:self.payMoneyLabel];
    
    UIButton *payBtn = [[UIButton alloc]init];
    [payBtn setTitle:@"立即购买" forState:UIControlStateNormal];
    [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [payBtn setBackgroundColor:GeneralBlueColor];
    [payBtn addTarget:self action:@selector(payClicked) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:payBtn];
    
    [contentView makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.equalTo(45);
    }];
    
    [moneyLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView.left).offset(12);
        make.centerY.equalTo(contentView.centerY);
    }];
    
    [self.payMoneyLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(moneyLabel.right);
        make.centerY.equalTo(contentView.centerY);
    }];
    
    [payBtn makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.equalTo(contentView);
        make.width.equalTo(107);
    }];
    
}

- (void)switchAction:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    if (sender.selected) {
        
        float money = self.model.price.floatValue - self.model.balance.floatValue;
        if (money > 0) {
            
            self.payMoney = [NSString stringWithFormat:@"%.2f",money];

        }
        else {
            self.payMoney = @"0.00";
        }
    }
    else {
        self.payMoney = self.model.price;
    }
    self.payMoneyLabel.text = [NSString stringWithFormat:@"￥%@",self.payMoney];

}

- (YYEBaseTableView *)tableView {
    
    if (!_tableView) {
        _tableView = [[YYEBaseTableView alloc]initwithDelegate:self];
    }
    return _tableView;
    
}

#pragma mark -- UITableview
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 3;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (section == 2) {
//        return 2;
        return 1;
    }else {
        return 1;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        YYECourseBuyInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:courseInfoCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.model = self.model;
        return cell;
        
    }else if (indexPath.section == 1) {
        
        YYEBalanceSwitchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:acountCell];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.priceLabel.text = [NSString stringWithFormat:@"￥%@",self.model.balance];
        [cell.moneyBtn addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventTouchUpInside];
        if (self.model.balance.floatValue > 0) {
            cell.moneyBtn.selected = YES;
            cell.moneyBtn.userInteractionEnabled = YES;

        }
        else {
            cell.moneyBtn.selected = NO;
            cell.moneyBtn.userInteractionEnabled = NO;

        }

        return cell;
        
    }else {
        
        YYERechargeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:paymentCell];
        cell.block = ^(NSInteger row) {
            if (row == 0) {
                
                self.payWay = @"2";
            }
            else {
                self.payWay = @"1";
                
            }
        };
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.row = indexPath.row;
        NSArray *names = @[@"微信支付",@"支付宝支付"];
        NSArray *imgNames = @[@"weixin",@"zhifubao"];
        cell.nameLabel.text = names[indexPath.row];
        cell.headerIV.image = [UIImage imageNamed:imgNames[indexPath.row]];
        
        if (indexPath.row == 0) {
            cell.lineView.backgroundColor = [UIColor whiteColor];
            cell.lineView.image = [UIImage imageNamed:@"Line"];

        }else {
            cell.lineView.hidden = YES;

        }
        
        return cell;
        
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        return 114;
        
    }else if (indexPath.section == 1) {
        
        return 40;
        
    }else {
        
        return 50;
        
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 35;
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
    contentView.backgroundColor = GeneralBackColor;
    
    UILabel *nameLabel = [[UILabel alloc]init];
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.font = [UIFont systemFontOfSize:14];
    [contentView addSubview:nameLabel];
    
    [nameLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(contentView.left).offset(WSCALE * 20);
        make.centerY.equalTo(contentView.centerY);
    }];
    
    if (section == 0) {
        nameLabel.text = @"课程详情";
    }else if (section == 1) {
        nameLabel.text = @"使用余额";
    }else if (section == 2) {
        nameLabel.text = @"支付方式";
    }
    
    return contentView;
    
}

// 立即购买
- (void)payClicked {
    
//    NSMutableDictionary *paramDic = [[NSMutableDictionary alloc] initWithCapacity:0];
//    [paramDic setValue:[LoginModel shareLogin].uid forKey:@"uid"];
//    [paramDic setValue:[LoginModel shareLogin].token forKey:@"token"];
//    [paramDic setValue:[LoginModel shareLogin].username forKey:@"username"];
//    [paramDic setValue:self.cid forKey:@"cid"];
    
//    // 1支付宝 2微信
//    if (self.payMoney.floatValue > 0) {// 第三方支付
//
//        if ([self.payWay isEqualToString:@"2"]) {
//            [paramDic setValue:[NSString getIPAddress:YES] forKey:@"spbill_create_ip"];
//            [paramDic setValue:@"0" forKey:@"is_balance"];
//        }
//        else if ([self.payWay isEqualToString:@"alipay"]) {
//            [paramDic setValue:@"0" forKey:@"is_balance"];
//
//        }
//        [paramDic setValue:self.payWay forKey:@"other_pay"];
//
//    }
//    else {
//
//        [paramDic setValue:@"1" forKey:@"is_balance"];
//
//    }
//    [AFNHelper post:Buy_now parameters:paramDic success:^(id responseObject) {
//
//        if ([responseObject[@"status"] isEqual:@1]) {
//            // 1支付宝 2微信
//
//            PayModel *model = [PayModel mj_objectWithKeyValues:responseObject[@"data"][@"info"]];
//
//            if ([responseObject[@"data"][@"type"] integerValue] == 1) {
//
//
//            }
//            else if ([responseObject[@"data"][@"type"] integerValue] == 2) {
//
//                //需要创建这个支付对象
//                PayReq *req = [[PayReq alloc] init];
//                //应用id
//                req.openID = model.appid;
//
//                // 商家商户号
//                req.partnerId = model.partnerid;
//
//                // 预支付订单这个是后台跟微信服务器交互后，微信服务器传给你们服务器的，你们服务器再传给你
//                req.prepayId = model.prepayid;//self.orderWithWX.prepayid;
//
//                // 根据财付通文档填写的数据和签名
//                //这个比较特殊，是固定的，只能是即req.package = Sign=WXPay
//                req.package = model.package;
//
//                // 随机编码，为了防止重复的，在后台生成
//                req.nonceStr = model.noncestr;//self.orderWithWX.noncestr;
//
//                // 这个是时间戳，也是在后台生成的，为了验证支付的
//                int timesta = [model.timestamp intValue];
//                UInt32 timestamp = (UInt32)timesta;
//                req.timeStamp = timestamp;
//
//                // 这个签名也是后台做的
//                req.sign = model.sign;//self.orderWithWX.sign;
//
//                //发送请求到微信，等待微信返回onResp
//                [WXApi sendReq:req];
//
//
//            }
//            else {
//
//                [self.view makeToast:@"购买成功"];
//
//                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    [self.navigationController popToRootViewControllerAnimated:YES];
//                });
//            }
//        }
//        else {
//            [self.view makeToast:responseObject[@"message"]];
//        }
//
//    } faliure:^(id error) {
//
//        NSLog(@"请求失败");
//
//    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
